var ep_excelApp;
var ep_excelWb;
//构造函数
function ExcelParser(filepath){
    this.destroy = ExcelParser_destroy;
    this.open = ExcelParser_open;
    this.parse = ExcelParser_parse;
    ep_excelApp = new ActiveXObject("Excel.Application");
    ep_excelApp.Visible = false;
    ep_excelWb = ep_excelApp.Workbooks;
    if (filepath) ExcelParser_open(filepath);
}

//把mht内的数据解析为二维数组对象
function ExcelParser_parse(){
    var ret = [];
    var rows = ep_excelWb(1).WorkSheets(1).UsedRange.Rows;
    if (!rows) return ret;
    for (var i = 1, rowsCount = rows.Count; i <= rowsCount; i++) {
        var rowCells = rows(i).Columns;
        var rowData = [];
        for (var j = 1, rowCellsCount = rowCells.Count; j <= rowCellsCount; j++) {
            var value = rowCells(j).Value || '';
            rowData.push(value);
        }
        ret.push(rowData);
    }
    return ret;
}

function ExcelParser_destroy(){
    ep_excelWb.Close();
    ep_excelApp.Quit();
    ep_excelWb = null;
    ep_excelApp = null;
    window.setTimeout("CollectGarbage();", 10);
}

//打开mht文件
function ExcelParser_open(filepath){
    ep_excelWb.Open(filepath);
}

//供外部调用的方法
/**
 * 解析mht文件并同步提交至form所定义的op
 * @param {String} excelFileControl file组件的name
 * @param {String} formName file组件所在的form的name
 * @return {Boolean} 返回结果,若有解析异常则返回false
 */
function ExcelParseAndSubmit(excelFileControl, formName){
    if (typeof excelFileControl != 'string' || typeof formName != 'string') return false;
    var ep, dataArr, dataArrStr, form, inputName = excelFileControl, dealFlag = false;
    try {
        ep = new ExcelParser();
        excelFileControl = document.getElementsByName(excelFileControl)[0];
        form = document.getElementsByName(formName)[0];
        if (!excelFileControl || !form) return false;
        ep.open(excelFileControl.value);
        dataArr = ep.parse();
        if (dataArr && dataArr.length > 0) {
            dataArrStr = ctp.data.jsonToStr(dataArr);
            //抽取form中的信息
            var action = form.action, flowActionName = form.flowActionName.value, sessionId = form.dse_sessionId.value;
            var url = [action, '?flowActionName=', flowActionName, '&dse_sessionId=', sessionId].join('');
            var reqData = {};
            reqData[inputName] = dataArrStr;
            //同步提交,注意没有设置dataType,若指定设置dataType为json会报错(但不阻止op的处理),导致去不到success那
            $.ajax({
                async: false,
                data: reqData,
                success: function(data){
                    var result = eval('(' + data + ')');
                    if (result.retCode === '0') dealFlag = true;
                },
                url: url,
                type: 'POST'
            });
        }
        return dealFlag;
    } 
    catch (e) {
        return false;
    }
    finally {
        try {
            ep.destroy();
        } 
        catch (e) {
        }
    }
}
